package com.ybear.ybutils.utils

import android.app.AppOpsManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi
import java.lang.reflect.Method

/**
 * 后台弹出界面权限
 */
class BackgroundPopupUiManager {
    companion object {
        @JvmStatic
        val instance by lazy { BackgroundPopupUiManager() }
    }

    /**
     * 是否打开了后台弹窗界面权限
     */
    fun isAllowedBackgroundPopupUi(context: Context): Boolean {
        return when ( Build.MANUFACTURER.lowercase() )  {
            "xiaomi" -> isAuthByXiaomi( context )
            "vivo" -> isAuthViVo( context )
            "oppo" -> isAuthOppo( context )
            "huawei" -> isAuthHuawei( context )
            else -> if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
                Settings.canDrawOverlays( context )
            } else {
                true
            }
        }
    }

    /**
     * 打开应用权限系统设置页面
     */
    fun startApplicationDetailsActivity(context: Context) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.parse("package:${context.packageName}")
        context.startActivity( intent )
    }

    // 小米权限判断
    private fun isAuthByXiaomi(context: Context): Boolean {
        val appOpsManager = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        return try {
            val op = 10021
            val method: Method = appOpsManager.javaClass.getMethod(
                "checkOpNoThrow",
                Int::class.javaPrimitiveType,
                Int::class.javaPrimitiveType,
                String::class.java
            )
            val result = method.invoke(
                appOpsManager, op, android.os.Process.myUid(), context.packageName
            ) as Int
            result == AppOpsManager.MODE_ALLOWED
        } catch (e: Exception) {
            e.printStackTrace()
            // 如果闪退，可能是安卓版本不支持，返回true
            true
        }
    }

    // ViVo 权限判断
    private fun isAuthViVo(context: Context): Boolean {
        val uri: Uri = Uri.parse(
            "content://com.vivo.permissionmanager.provider.permission/start_bg_activity"
        )
        val selection = "pkgname = ?"
        val selectionArgs = arrayOf(context.packageName)
        return try {
            context.contentResolver.query(
                uri, null, selection, selectionArgs, null
            )?.use { cursor ->
                if ( cursor.moveToFirst() ) {
                    val index = cursor.getColumnIndex( "currentstate" )
                    if( index > -1 ) cursor.getInt( index ) == 0 else false
                } else {
                    false
                }
            } ?: false
        } catch (e: Exception) {
            e.printStackTrace()
            // 如果闪退，可能是安卓版本不支持，返回true
            true
        }
    }

    // Oppo 权限判断
    private fun isAuthOppo(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.canDrawOverlays( context )
        } else {
            true
        }
    }

    // 华为权限判断
    private fun isAuthHuawei(context: Context): Boolean {
        try {
            val intent = Intent()
            intent.action = "huawei.intent.action.NOTIFICATIONMANAGER"
            return context.packageManager.resolveActivity(intent, 0) != null
        } catch (e: Exception) {
            e.printStackTrace()
            // 如果闪退，可能是安卓版本不支持，返回true
            return true
        }
    }
}